from google.appengine.api import mail
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import login_required
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson

class SendShareRequest(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user is None:
          self.response.out.write('Please Login')
          return

        json_arr = {}
        json_arr = simplejson.loads(self.request.body)

        message = mail.EmailMessage()
        message.sender = user.email()
        message.subject = "live-board share session request"
        message.body = """
I've invited you to share my liveBoard at live-board.appspot.com!
<br><br>
To accept this invitation, click the following link,
or copy and paste the URL into your browser's address
bar:
<br><br>
http://live-board.appspot.com/index.html?%s
        """  % (json_arr['link'])

        to_addr = json_arr['contacts']
        for email in to_addr:
          if mail.is_email_valid(email):
            self.response.out.write(email + "<br>")
            #message.to = email 
            #message.send()

        self.response.out.write("<br>Message sent:<br>")
        self.response.out.write(message.subject + "<br>")
        self.response.out.write(message.body + "<br>")


    def get(self):
        user = users.get_current_user()
        if user is None:
          self.response.out.write('Please Login')
          return

        to_addr = self.request.get("to")
        if not mail.is_email_valid(to_addr):
            self.response.out.write('Invalid Email')
            return 

        message = mail.EmailMessage()
        message.sender = user.email()
        message.to = to_addr
        message.subject = "invite"
        message.body = """
I've invited you to share my liveBoard at live-board.appspot.com!

<br>To accept this invitation, click the following link,
or copy and paste the URL into your browser's address
bar:

http://live-board.appspot.com/join?gid=1234
        """ 

        #message.send()


application = webapp.WSGIApplication(
                                     [('/sharereq', SendShareRequest)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
